package com.chinatelecom.ifree.business.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DSAUtil {
	private static final Log logger = LogFactory.getLog(DSAUtil.class);

	public static byte[] sig(byte[] sigText, String KeyPassword, String KeystoreAlias, String KeyStorePath) {
		char[] kpass;
		// int i;
		try {
			KeyStore ks = KeyStore.getInstance("JKS");
			FileInputStream ksfis = new FileInputStream(KeyStorePath);
			BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
			/*kpass = new char[KeyPassword.length()];
			for (i = 0; i < KeyPassword.length(); i++)
			    kpass[i] = KeyPassword.charAt(i);*/
			kpass = KeyPassword.toCharArray();
			ks.load(ksbufin, kpass);
			PrivateKey priv = (PrivateKey) ks.getKey(KeystoreAlias, kpass);
			Signature rsa = Signature.getInstance("SHA1withDSA");
			rsa.initSign(priv);
			rsa.update(sigText);
			byte[] sig = rsa.sign();
			// System.out.println("sig is done");
			return sig;
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
	}

	public static boolean veriSig(byte[] updateData, byte[] sigedText, String certPath) {
		try {
			CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
			FileInputStream fin = new FileInputStream(certPath);
			X509Certificate certificate = (X509Certificate) certificatefactory.generateCertificate(fin);
			PublicKey pub = certificate.getPublicKey();
			Signature dsa = Signature.getInstance("SHA1withDSA");
			dsa.initVerify(pub);
			dsa.update(updateData);
			return dsa.verify(sigedText);
		} catch (Exception e) {
			logger.error("", e);
			return false;
		}
	}

}
